package com.huawei.hms.framework.network.restclient.hwhttp.dns;

import android.text.TextUtils;
import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.common.Utils;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DNManager.DnsFail;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.cache.CacheManager;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver.DNResolverManager;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver.dnkeeper.DNKeeper;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver.dnkeeper.DomainResult;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver.dnkeeper.DomainResult.Address.Builder;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnstask.TaskManager;
import com.huawei.hms.framework.network.util.ErrorCodeUtil;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

public class DnsUtil {
    public static final int DEFAULT_DNS_TIMEOUT = 10000;
    public static final int MAX_DNS_TIMEOUT = 15000;
    private static final String TAG = "DnsUtil";
    private static int dnsTimeout = 10000;

    public static int getDnstime() {
        return dnsTimeout;
    }

    public static void setDnstime(int i) {
        if (i > 0 && i <= MAX_DNS_TIMEOUT) {
            dnsTimeout = i;
        }
    }

    public static List<InetAddress> convertAddress(List<String> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList();
        }
        List<InetAddress> arrayList = new ArrayList(list.size());
        for (String str : list) {
            try {
                arrayList.add(InetAddress.getByName(str));
            } catch (UnknownHostException e) {
                Logger.w(TAG, "convertAddress failed, ip:" + str);
            }
        }
        return arrayList;
    }

    public static DomainResult convertAddress(InetAddress[] inetAddressArr) {
        DomainResult domainResult = new DomainResult();
        if (inetAddressArr != null && inetAddressArr.length > 0) {
            for (InetAddress inetAddress : inetAddressArr) {
                domainResult.addAddress(new Builder().ttl(DnsConfig.defaultCacheTtl).value(inetAddress.getHostAddress()).type(isIPv4(inetAddress) ? "A" : "AAAA").build());
            }
        }
        return domainResult;
    }

    public static List<InetAddress> getIPListByHost(String str) throws UnknownHostException {
        List arrayList = new ArrayList();
        if (TextUtils.isEmpty(str)) {
            return arrayList;
        }
        if (DNManager.getInstance().isEnableDnsCache()) {
            DomainResult lookup = CacheManager.lookup(str);
            if (isInvalidDnsResult(lookup)) {
                Logger.v(TAG, "LocalDNS or DNKeeper host: " + str);
                DNManager.getInstance().setDnsCache(str, 0);
                lookup = DNResolverManager.queryHostSync(str, DNManager.getInstance().getResolverSource(str));
            } else {
                Logger.v(TAG, "Memory Cache host:" + str);
                DNManager.getInstance().setDnsCache(str, 1);
                if (DNManager.getInstance().getResolverSource(str) == 4) {
                    DNResolverManager.dnsLazyUpdate(str, DNManager$ResolveTriggerType.DNS_LAZY_UPDATE);
                }
            }
            if (!isIpListEmpty(lookup)) {
                arrayList = ipFilter(lookup);
                saveIp(arrayList, str);
                List<InetAddress> convertAddress = convertAddress(arrayList);
                if (!convertAddress.isEmpty()) {
                    return convertAddress;
                }
            }
        }
        return localDnsLookup(str);
    }

    private static void saveIp(List<String> list, String str) {
        if (list != null && list.size() > 0) {
            DnsFail dnsFail = new DnsFail();
            dnsFail.setIp((String) list.get(0));
            DNManager.getInstance().addDns(str, dnsFail);
        }
    }

    public static <T> void doRespone(long j, String str, T t) {
        Logger.v(TAG, "enter DnsUtil.doRespone");
        if (!DNManager.getInstance().isEnableDnsCache()) {
            return;
        }
        if (TextUtils.isEmpty(str) || t == null) {
            Logger.w(TAG, "invalid parameter");
            return;
        }
        DNKeeper dNKeeper = DNManager.getInstance().getDNKeeper();
        int i = 0;
        if (t instanceof IOException) {
            i = ErrorCodeUtil.getErrorCode((IOException) t);
        } else if (t instanceof Integer) {
            i = ErrorCodeUtil.getErrorCode(((Integer) t).intValue());
        }
        if (!(dNKeeper == null || i == 0)) {
            dnsStateChage(j, str);
        }
        if (i != 0) {
            CacheManager.removeInvalidIP(str);
            if (dNKeeper != null) {
                dNKeeper.removeDns(str);
                DnsFail dns = DNManager.getInstance().getDns(str);
                if (dns != null) {
                    dns.setCode(i);
                    return;
                }
                return;
            }
            return;
        }
        DNManager.getInstance().deleteDns(str);
    }

    public static boolean isIpListEmpty(DomainResult domainResult) {
        return domainResult == null || domainResult.isEmpty();
    }

    public static boolean isInvalidDnsResult(DomainResult domainResult) {
        return domainResult == null || domainResult.isTimeOut();
    }

    public static boolean isIPv4(InetAddress inetAddress) {
        if (inetAddress instanceof Inet4Address) {
            return true;
        }
        return false;
    }

    public static boolean isIPv4(String str) {
        try {
            if (InetAddress.getByName(str) instanceof Inet4Address) {
                return true;
            }
        } catch (UnknownHostException e) {
            Logger.w(TAG, "Get Address from literal IP failed, Address:" + str);
            return false;
        } catch (SecurityException e2) {
            Logger.w(TAG, "Get Address from literal IP failed, Address:" + str);
            return false;
        }
        return false;
    }

    private static List<String> ipFilter(DomainResult domainResult) {
        List<String> ipList = domainResult.getIpList();
        removeDuplicate(ipList);
        return ipList;
    }

    private static <T> void removeDuplicate(List<T> list) {
        if (list != null) {
            Collection linkedHashSet = new LinkedHashSet(list.size());
            linkedHashSet.addAll(list);
            list.clear();
            list.addAll(linkedHashSet);
        }
    }

    private static void dnsStateChage(long j, String str) {
        int i = 4;
        if (!TextUtils.isEmpty(str)) {
            DnsInfo resolverDnsInfo = DNManager.getInstance().getResolverDnsInfo(str);
            if (resolverDnsInfo == null) {
                resolverDnsInfo = new DnsInfo();
            } else if (resolverDnsInfo.getStateUpdateTime() > j) {
                return;
            }
            switch (DNManager.getInstance().getResolverSource(str)) {
                case 4:
                    i = 5;
                    break;
                case 5:
                    if (DnsConfig.fileCacheStrategy == 1) {
                        i = 6;
                        break;
                    }
                    break;
            }
            resolverDnsInfo.setState(i);
            resolverDnsInfo.setStateUpdateTime(Utils.getCurrentTime(true));
            DNManager.getInstance().setResolverSource(str, resolverDnsInfo);
            Logger.v(TAG, "Switch resolve source, from: %s, to: %s", Integer.valueOf(r2), Integer.valueOf(resolverDnsInfo.getState()));
        }
    }

    public static List<InetAddress> localDnsLookup(String str) throws UnknownHostException {
        DNManager.getInstance().setDnsCache(str, 0);
        return TaskManager.getInstance().localDnslookup(str);
    }
}
